package com.chaodev.base.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.InteractionQrcodeDto;
import com.chaodev.base.model.InteractionQrcode;
import com.chaodev.base.model.Result;
import com.chaodev.base.model.ResultEnum;
import com.chaodev.base.model.UserInfo;
import com.chaodev.base.service.InteractionQrcodeService;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;

import static com.chaodev.base.utils.Base64EnOut.Base64Encode;

@RestController
@RequestMapping("interactionQrcode")
@Api(tags = "互动二维码")
public class InteractionQrcodeController {

    Logger logger= LoggerFactory.getLogger(InteractionQrcodeController.class);

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Autowired
    private InteractionQrcodeService interactionQrcodeService;

    @Autowired
    private CommController commController;

    @Resource
    Environment env;

    @PostMapping(value = "/addInteractionQrcode")
    @ApiOperation(value = "新增互动二维码")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result addInteractionQrcode(@RequestBody InteractionQrcode interactionQrcode, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }

            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            interactionQrcode.setCreateUser(userInfo.getUserId());
            logger.info("执行方法add");
            long l = System.currentTimeMillis();
            String uuidFileName=l+".jpg";
            QrConfig qrConfig = new QrConfig(300,300);
            qrConfig.setMargin(3);
            qrConfig.setForeColor(Color.black.getRGB());
//            Result generateQrUrl = commController.getGenerateQrUrl(interactionQrcode.getContent(), interactionQrcode.getName(), request, response);
            QrCodeUtil.generate(interactionQrcode.getContent().replaceAll("<p>","").replaceAll("</p>",""),qrConfig, FileUtil.file(env.getProperty("fileBaseStoreDIR")+"/"+uuidFileName));

            StringBuilder serverPath = new StringBuilder();
            serverPath.append(env.getProperty("serverName"));
            serverPath.append(request.getContextPath());
            String fileUrl = serverPath+env.getProperty("downloadApi") + uuidFileName + "&basepath=" + Base64Encode("");
            interactionQrcode.setQrUrl(fileUrl);
//            if (generateQrUrl.getCode() != null && generateQrUrl.getCode().equals(ResultEnum.SUCCESS.getCode())){
//                Map<String, Object> map = (Map<String, Object>) generateQrUrl.getData();
//                interactionQrcode.setQrUrl(map.get("url") == null ? "" : (String)map.get("url"));
//            }

            if (interactionQrcodeService.addInteractionQrcode(interactionQrcode)){
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("操作成功");
            }else {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("操作失败");
            }
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcode.toString(), "新增互动二维码", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/editInteractionQrcode")
    @ApiOperation(value = "修改互动二维码")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result editInteractionQrcode(@RequestBody InteractionQrcode interactionQrcode, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            if (interactionQrcode.getId() == null || "".equals(interactionQrcode.getId())) {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("缺少id");
                return result;
            }
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            interactionQrcode.setUpdateUser(userInfo.getUserId());
//            Result generateQrUrl = commController.getGenerateQrUrl(interactionQrcode.getContent(), interactionQrcode.getName(), request, response);
//            if (generateQrUrl.getCode() != null && generateQrUrl.getCode().equals(ResultEnum.SUCCESS.getCode())){
//                Map<String, Object> map = (Map<String, Object>) generateQrUrl.getData();
//                interactionQrcode.setQrUrl(map.get("url") == null ? "" : (String)map.get("url"));
//            }
            long l = System.currentTimeMillis();
            String uuidFileName=l+".jpg";
            QrConfig qrConfig = new QrConfig(300,300);
            qrConfig.setMargin(3);
            qrConfig.setForeColor(Color.CYAN.getRGB());
//            Result generateQrUrl = commController.getGenerateQrUrl(interactionQrcode.getContent(), interactionQrcode.getName(), request, response);
            QrCodeUtil.generate(interactionQrcode.getContent(),qrConfig, FileUtil.file(env.getProperty("fileBaseStoreDIR")+"/"+uuidFileName));

            StringBuilder serverPath = new StringBuilder();
            serverPath.append(env.getProperty("serverName"));
            serverPath.append(request.getContextPath());
            String fileUrl = serverPath+env.getProperty("downloadApi") + uuidFileName + "&basepath=" + Base64Encode("");
            interactionQrcode.setQrUrl(fileUrl);
            if (interactionQrcodeService.editInteractionQrcode(interactionQrcode)){
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("操作成功");
            }else {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("操作失败");
            }
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcode.toString(), "修改互动二维码", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/saveInteractionQrcode")
    @ApiOperation(value = "保存互动二维码")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result saveInteractionQrcode(@RequestBody InteractionQrcode interactionQrcode, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        logger.info("执行方法");
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            interactionQrcode.setCreateUser(userInfo.getUserId());
//            Result generateQrUrl = commController.getGenerateQrUrl(interactionQrcode.getContent(), interactionQrcode.getName(), request, response);
//            if (generateQrUrl.getCode() != null && generateQrUrl.getCode().equals(ResultEnum.SUCCESS.getCode())){
//                Map<String, Object> map = (Map<String, Object>) generateQrUrl.getData();
//                interactionQrcode.setQrUrl(map.get("url") == null ? "" : (String)map.get("url"));
//            }
            logger.info("执行方法save");
            long l = System.currentTimeMillis();
            String uuidFileName=l+".jpg";
            QrConfig qrConfig = new QrConfig(300,300);
            qrConfig.setMargin(3);
            qrConfig.setForeColor(Color.ORANGE.getRGB());
//            Result generateQrUrl = commController.getGenerateQrUrl(interactionQrcode.getContent(), interactionQrcode.getName(), request, response);
            String content=interactionQrcode.getContent().replaceAll("<p>","").replaceAll("</p>","").replaceAll("&amp;","&");
            System.out.println("content = " + content);
            QrCodeUtil.generate(content,qrConfig, FileUtil.file(env.getProperty("fileBaseStoreDIR")+"/"+uuidFileName));
            StringBuilder serverPath = new StringBuilder();
            serverPath.append(env.getProperty("serverName"));
            serverPath.append(request.getContextPath());
            String fileUrl = serverPath+env.getProperty("downloadApi") + uuidFileName + "&basepath=" + Base64Encode("");
            interactionQrcode.setQrUrl(fileUrl);
            if (interactionQrcodeService.saveInteractionQrcode(interactionQrcode)){
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("操作成功");
            }else {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("操作失败");
            }
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcode.toString(), "保存互动二维码", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/removeInteractionQrcode")
    @ApiOperation(value = "删除互动二维码")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result removeInteractionQrcode(@RequestBody InteractionQrcode interactionQrcode, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            if (interactionQrcode.getId() == null || "".equals(interactionQrcode.getId())) {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("缺少id");
                return result;
            }
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            if (interactionQrcodeService.removeInteractionQrcode(interactionQrcode)){
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("操作成功");
            }else {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("操作失败");
            }
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcode.toString(), "删除互动二维码", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getInteractionQrcodeList")
    @ApiOperation(value = "查询互动二维码列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getInteractionQrcodeList(@RequestBody InteractionQrcodeDto interactionQrcodeDto, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);

            result.setData(interactionQrcodeService.getInteractionQrcodeList(interactionQrcodeDto));
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("查询成功");
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcodeDto.toString(), "查询互动二维码列表", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getInteractionQrcodeById")
    @ApiOperation(value = "查询单条互动二维码")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getInteractionQrcodeById(@RequestBody InteractionQrcode interactionQrcode, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            if (interactionQrcode.getId() == null || "".equals(interactionQrcode.getId())) {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("缺少id");
                return result;
            }
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);

            result.setData(interactionQrcodeService.getInteractionQrcodeById(interactionQrcode));
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("查询成功");
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcode.toString(), "查询单条互动二维码", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getInteractionQrcodePage")
    @ApiOperation(value = "查询互动二维码分页")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getInteractionQrcodePage(@RequestBody InteractionQrcodeDto interactionQrcodeDto, HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            if(interactionQrcodeDto.getPage() == null || interactionQrcodeDto.getPage() == 0
                    || interactionQrcodeDto.getRows() == null || interactionQrcodeDto.getRows() == 0){
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("缺少页码或条数");
                return result;
            }

            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            result.setData(interactionQrcodeService.getInteractionQrcodePage(interactionQrcodeDto));
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("查询成功");
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(interactionQrcodeDto.toString(), "查询互动二维码分页", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }
    
}
